from flask import Blueprint, Response
import requests
from cache import cache

unpkg_base_url = "https://unpkg.com/"
unpkg_proxy = Blueprint('unpkg_proxy', __name__)

@unpkg_proxy.route('/unpkg/<path:subpath>')
@cache.memoize(timeout=3600)
def unpkg(subpath):
    return proxy_request(unpkg_base_url, subpath)


def proxy_request(base_url, subpath):

    full_url = f"{base_url}{subpath}"

    response = requests.get(full_url, headers={"Accept-Encoding": "identity"})
    content = response.content

    headers = {key: value for key, value in response.headers.items()}
    headers['Transfer-Encoding'] = 'identity'

    return Response(content, status=response.status_code, headers=headers, content_type=response.headers['content-type'])
